/**************************** PLAYER ******************************************/
var paused = true;
var loaded = false;
var statusIndicator = '';
var pausition = 0;
var scrobbleTimeOut;
var currentTrack = '';
var importLock = false;
/**
 * Second to string conversion
 */
function timeString(time)
{
  var H;
  var S;
  var M;
  time = time/1000;
  if(time>=3600){H = Math.floor(time/3600);}else{H=0}
  if(time>=60){M = Math.floor((time/60) - H * 60);}else{M=0}
  S = Math.floor(time - (H * 3600 + M * 60));
  if(H<10){H='0'+H;}
  if(M<10){M='0'+M;}
  if(S<10){S='0'+S;}
  return H+':'+M+':'+S;
}


/**
 *Javascript trim
 */
function trim(s)
{
    return s.replace(/^\s+/, '').replace(/\s+$/, '');
}


/**
 *Returns movie object
 */
function thisMovie(movieName)
{
  if(navigator.appName.indexOf("Microsoft") != -1)
  {
    return window[movieName];
  }
  else
  {
    return document[movieName];
  }
}

/**
 * Tries to play a url as mp3
 */
function playUrl(soundUrl)
{
  clearTimeout(scrobbleTimeOut);
  scrobbleTimeOut = setTimeout("scrobble()",30000);
  loaded = false;
  paused = false;

  thisMovie('fookinPlay').stopSound();
  thisMovie('fookinPlay').playSound(soundUrl);

  $('#btnPlayer').removeClass('btnPlay').addClass('btnPause');
  $('#playerLbl').empty().append(str.ui_contacting_site);

}

function scrobble()
{
  //alert('scrobble time !');
  $.ajax({
    data:{
      action:'scrobble',
      trackId:currentTrack,
      token:$('#token').val()
    }
  });
}

function setTags(id3Artist,id3Album,id3Track)
{
  alert(id3Artist+' / '+id3Album+' / '+id3Track);
}

function togglePause()
{
  if(paused)
  {
    thisMovie('fookinPlay').skipTo(pausition/1000);
    paused = false;
    scrobbleTimeOut = setTimeout("scrobble()",30000);
    $('#btnPlayer').removeClass('btnPlay').addClass('btnPause');
  }
  else
  {
    pausition = thisMovie('fookinPlay').getPosition();
    paused = true;
    thisMovie('fookinPlay').stopSound();
    clearTimeout(scrobbleTimeOut);
    $('#btnPlayer').removeClass('btnPause').addClass('btnPlay');
  }
}

function sLoaded()
{
  loaded = true;
}



function updateSlider()
{
	if(loaded == false)
	{
		var statusIndicator = ' ['+str.ui_loading+']';
  }
  else
  {
    if(paused == true)
		{
      var statusIndicator = ' ['+str.ui_pause+']';
    }
    else
    {
      var statusIndicator = '';
    }
  }

   mySongPosition = thisMovie('fookinPlay').getPosition();
	 mySongDuration = thisMovie('fookinPlay').getDuration();

   if(mySongDuration > 0 && mySongPosition >0)
    {
      progress = mySongPosition*100/mySongDuration;
      $("#playerCursor").css({left:progress+'%'});
      label = timeString(mySongPosition) + " / " + timeString(mySongDuration) + statusIndicator;
      $('#playerLbl').empty().append(label);
    }

}


/******************************** GENERAL *************************************/


function GeneratePassword() {

    var length=8;
    var sPassword = "";

    var noPunction = true;
    var randomLength = false;

    if (randomLength) {
        length = Math.random();

        length = parseInt(length * 100);
        length = (length % 7) + 6
    }


    for (i=0; i < length; i++) {

        numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }

        sPassword = sPassword + String.fromCharCode(numI);
    }


    return sPassword;
}

function getRandomNum() {

    // between 0 - 1
    var rndNum = Math.random()

    // rndNum from 0 - 1000
    rndNum = parseInt(rndNum * 1000);

    // rndNum from 33 - 127
    rndNum = (rndNum % 94) + 33;

    return rndNum;
}

function checkPunc(num) {

    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }

    return false;
}

function is_numeric(num)
{
	var exp = new RegExp("^[0-9-.]*$","g");
	return exp.test(num);
}

/**
 * open Iframe
 */
function openMczBrowser(url)
{
  window.open(url);
  //$('#wikiframe').attr('src',url);$('#iframeContainer').jqm({modal:false}).jqmShow();
}

/**
 * Display help message
 */
function help(msg)
{
  if(msg != null)
  {
    $('#help').empty().append(msg);
  }
}

/**
 * Add url to library
 */
function addToLibrary(distantUrl)
{
  if(importLock)
  {
    alert(str.err_import_locked);
    return false;
  }
    importLock = true;
    $.ajax({
    dataType: "json",
      data:{
        action:'addToLibrary',
        url:distantUrl,
        token:$('#token').val()
      },
      timeout:30000,
      success:function(jsonObj){
        importLock = false;
        //alert(jsonObj.res);
        if(jsonObj == true)
        {
          alert(str.ui_added_to_import_cue);
        }
        else
        {
          alert(str.err_cant_add_to_import_cue);
        }
      },
      error:function(requestObj,errString,exceptionObj){
        alert(str.err_long_import);
        importLock = false;
      }
    });
}

/**
 *Keep session alive
 */
function stayAwake()
{
  $.post("?c=ajax");
}

/***************************** PodCast ****************************************/

/**
 * Add podcast to database
 */
function addPodcast()
{
  var distantUrl = prompt(str.hlp_add_podcast, "http://");
  if (distantUrl == null || distantUrl == '' || distantUrl =='http://')
  {
    return false;
  }
  $.ajax({
  dataType: "json",
    data:{
      action:'addpodcast',
      url:distantUrl,
      token:$('#token').val()
    },
    success:function(jsonObj){
      $('#podcastsList').empty().append(jsonObj.html);
      loadPodcast(distantUrl);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_podcast_delete);
    }
  });
}

/**
 * Remove podcast from database
 */
function deletePodcast(distantUrl)
{
  if(distantUrl == '' || distantUrl == 'empty')
  {
    return false;
  }
  if(confirm(str.ui_confirm_delete_podcast+'\n\n'+distantUrl))
  {

    $.ajax({
      dataType: "json",
      data:{
        action:'deletepodcast',
        url:distantUrl,
        token:$('#token').val()
        },
      success:function(jsonObj){
        if(jsonObj.html != '')
        {
          $('#podcastsList').empty().append(jsonObj.html);
          $('#podcastView').empty();
        }
      },
      error:function(requestObj,errString,exceptionObj){
        alert(str.err_podcast_delete);
      }
    });
  }
}

/**
 * Load podcast to podcast view
 */
function loadPodcast(distantUrl)
{
  if(distantUrl == 'empty'){return false;}

  $.ajax({
    dataType: "json",
    data:{
      action:'getpodcast',
      url:distantUrl,
      token:$('#token').val()
    },
    success:function(jsonObj){
      $('#podcastView').empty().append(jsonObj.html);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_podcast_not_found);
    }
  });
}


/********************************* CUELIST ************************************/

function snapshotCueList()
{
  var name = prompt(str.hlp_enter_playlist_name, "");
  if(name == null)
  {
    return false;
  }
  if(trim(name) == '')
  {
    alert(str.err_enter_playlist_name);
    return false;
  }
  if(name !='' && name != null)
  {
    $.ajax({
      dataType: "json",
      data:{
        action:"snapshotCueList",
        name:name,
        token:$('#token').val()
      },
      success:function(jsonObj){
        if(jsonObj.response == true)
        {
          $('#plsList').empty().append(jsonObj.list);
          //$('#onglets').triggerTab(3);
          alert(str.ui_create_playlist_ok);
        }
        else
        {
          alert(str.err_cant_create_playlist);
        }
      },
      error:function(requestObj,errString,exceptionObj){
        alert(str.err_cant_create_playlist);
      }
    });
  }
}

function updateCueOrder()
{
  serial = $.SortSerialize('cueList');
  $.ajax({
    data:{
      action:"updateCueOrder",
      hash:serial.hash,
      token:$('#token').val()
    }
  });
}

function refreshCue()
{
  $.ajax({
    dataType: "json",
    data:{
      token:$('#token').val(),
      action:'refreshCue'
      },
      timeout:3000,
      async:false,
    success:function(jsonObj){
      $('#cueList').empty().append(jsonObj.html).Sortable({
        accept :'sortableItem',
        axis:'vertically',
        containment:'cueList',
        handle:'.handle',
        helperclass : 'cueItemHelper',
        opacity: 	0.5,
        onchange:function(){updateCueOrder();}
      });
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
  });
}

/**
 * Add item to cue
 *
 * @param string type mczid or url
 * @param string label what to display in the list
 * @param string res_id ressource identifier, either song id or url
 */
function addToCue(type,label,res_id)
{
  $.ajax({
    dataType: "json",
    data:{
      token:$('#token').val(),
      action:'addToCue',
      res_id:res_id,
      type:type,
      label:label
      },
      timeout:3000,
      async:false,
    success:function(jsonObj){
      //alert('success');
      //$('#cueList').append(jsonObj.item).SortableAddItem(document.getElementById(jsonObj.id));
      refreshCue();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
  });
}

function playNext()
{
  //loaded =false;
  $.ajax({
    dataType: "json",
    data:{
      token:$('#token').val(),
      action:'getNext'
      },
    success:function(jsonObj){
      if(jsonObj == false)
      {
        alert(str.err_no_rights);
        return false;
      }
      if(jsonObj == 'file unavailable')
      {
				alert(str.err_file_unavailable);
				return false;
			}
      if(jsonObj.url != null)
      {
        $('#currLabel').empty().append(jsonObj.label);
        highlightItem(jsonObj.id);
        playUrl(jsonObj.url);
        currentTrack = jsonObj.id;
      }
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_cant_play);
    }
  });
}

function play(itemId)
{
  $.ajax({
    dataType: "json",
    data:{
      token:$('#token').val(),
      action:'getItemById',
      itemId:itemId
      },
    success:function(jsonObj){
      if(jsonObj == false)
      {
        alert(str.err_no_rights);
        return false;
      }
      if(jsonObj == 'file unavailable')
      {
				alert(str.err_file_unavailable);
				return false;
			}
      $('#currLabel').empty().append(jsonObj.label);
      highlightItem(jsonObj.id);
      playUrl(jsonObj.url);
      currentTrack = jsonObj.id;
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_cant_play+' : '+errString);
    }
  });
}

function highlightItem(itemId)
{
  $('.lblCue').removeClass("playinItem");
  $('#'+itemId+' > .lblCue').addClass("playinItem");
}

function removeAllFromCue()
{
  $('.sortableItem').each(
    function(){
      removeFromCue(this.id);
    }
  );
}

function removeFromCue(id)
{
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'removeFromCue',
    id:id
    },
    async:false,
    timeout:1000,
    success:function(jsonObj){
      //alert(jsonObj.id);
      if(jsonObj.response == 'ok')
      {
        //$('#'+id).hide(null,function(){$('#'+id).remove();});
        $('#'+id).remove();
      }
      else
      {
        alert(str.err_cant_remove_from_cue);
      }
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_cant_remove_from_cue);
    }
 });
}

/******************************** PLAYLISTS ***********************************/


function deletePlaylist(plsId)
{
  if(plsId == 'empty')
  {
    return false;
  }
  if(confirm(str.ui_confirm_delete_playlist))
  {
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'deletePlaylist',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#plsList').empty().append(jsonObj.list);
      $('#playlistSpace').empty();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
  }
}

function displayPls(plsId)
{
  if(plsId != 'empty')
  {
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'displayPls',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#playlistSpace').empty().append(jsonObj.response);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
  }
}

function addPlsToCue(plsId)
{
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'addPlsToCue',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#cueList').empty().append(jsonObj.response);
      $('#cueList').Sortable({
        accept :'sortableItem',
        axis:'vertically',
        containment:'cueList',
        handle:'.handle',
        helperclass : 'cueItemHelper',
        opacity: 	0.5,
        onchange:function(){updateCueOrder();}
      });
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
}

function cueToPls(plsId)
{
  if(confirm(str.ui_confirm_cue_to_pls))
  {
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'cueToPls',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#playlistSpace').empty().append(jsonObj.response);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
  }
}

function stopPod(plsId)
{
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'stopPod',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#playlistSpace').empty().append(jsonObj.response);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
}

function startPod(plsId)
{
  $.ajax({
   dataType: "json",
   data:{
    token:$('#token').val(),
    action:'startPod',
    plsId:plsId
    },
    success:function(jsonObj){
      $('#playlistSpace').empty().append(jsonObj.response);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
    });
}

/******************************** LIBRARY *************************************/

function checkAll()
{
  $('.checker').each(function() {
      if(this.checked == true)
      {
        this.checked = false;
      }
      else
      {
        this.checked = true;
      }
  });
}

function taggerSwitch()
{
  if($('#selectedAction').val() == 'tag')
  {
    $('#tagger').show();
    $('#playlistSelect').hide();
  }
  else if($('#selectedAction').val() == 'addToPls')
  {
    $('#tagger').hide();
    $('#playlistSelect').empty().load('?c=ajax',{action:'listPls',token:$('#token').val()}).show();
  }
  else
  {
    $('#tagger').hide();
    $('#playlistSelect').hide();
  }
}


/**
 *What to do for checked items
 */
function checkAction()
{
  var checkersHash = '';
  /**
   *Tag files
   */
  if($('#selectedAction').val() == 'tag')
  {
    $('.checker').each(function() {
      if(this.checked == true)
      {
        checkersHash += '|' + this.id;
/*
        $.ajax({
          data:{
            token:$('#token').val(),
            action:'setTag',
            songId:this.id,
            tag:$('#tagField').val(),
            tagValue:$('#tagValue').val()
          },
          success:function(msg){
            refreshLib();
          }
        });
*/
      }
    });

    $.ajax({
      data:{
        token:$('#token').val(),
        action:'setTags',
        songIds:checkersHash,
        tag:$('#tagField').val(),
        tagValue:$('#tagValue').val()
      },
      timeout:30000,
        success:function(msg){
          refreshLib();
        },
        error:function(requestObj,errString,exceptionObj){
          alert(str.err_ajax_failed);
          refreshLib();
        }
    });
  }
  if($('#selectedAction').val() == 'delete')
  {
    var nbSongs = 0;
    $('.checker').each(function() {
      if(this.checked == true)
      {
        checkersHash += '|' + this.id;
        //nbSongs++;
      }
    });
    if(confirm(str.ui_confirm_delete_songs))
    {
      //alert(nbSongs);
      $.ajax({
        data:{
          token:$('#token').val(),
          action:'deleteSongs',
          songIds:checkersHash
        },
        success:function(){
          refreshLib();
        },
        error:function(requestObj,errString,exceptionObj){
          alert(str.err_cant_remove_from_cue);
        }
      });
    }
  }
  if($('#selectedAction').val() == 'addToCue')
  {
    $('.checker').each(function(){
      if(this.checked == true)
      {
        checkersHash += '|' + this.id;
        this.checked = false;
        //addToCue('mczid','',this.id);
      }
    });
    
    // multiple add
    $.ajax({
    dataType: "json",
    data:{
      token:$('#token').val(),
      action:'addMultipleToCue',
      hash:checkersHash,
      },
      timeout:3000,
      async:false,
    success:function(jsonObj){
      //alert('success');
      //$('#cueList').append(jsonObj.item).SortableAddItem(document.getElementById(jsonObj.id));
      refreshCue();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
  });
    
  }
  if($('#selectedAction').val() == 'addToPls')
  {
    $('.checker').each(function() {
      if(this.checked == true)
      {
        checkersHash += '|' + this.id;
      }
    });
    if($('#plsSelect2').val() == 'new')
    {
      var plsName = prompt(str.hlp_enter_playlist_name, "");
      if(plsName == null)
      {
        return false;
      }
      if(trim(plsName) == '')
      {
        alert(str.err_enter_playlist_name);
        return false;
      }
      var plsId = '';
      //alert('nouvelle playlist : '+ plsName + ' -> ' + checkersHash);
    }
    else
    {
      var plsName = '';
      var plsId = $('#plsSelect2').val();
    }
    
    $.ajax({
      dataType: "json",
      data:{
        action:"hashToPls",
        name:plsName,
        id:plsId,
        hash:checkersHash,
        token:$('#token').val()
      },
      success:function(jsonObj){
        if(jsonObj.response == true)
        {
          $('#plsList').empty().append(jsonObj.list);
          $('#playlistSpace').empty();
          alert(str.ui_add_to_pls_ok);
          $('.checker').each(function(){
            this.checked = false;
          });
        }
        else
        {
          alert(str.err_cant_create_playlist);
        }
      },
      error:function(requestObj,errString,exceptionObj){
        alert(str.err_ajax_failed);
      }
    });
  }
}

function tag(songId,songField,fieldValue)
{
  $.ajax({
   data:{
    token:$('#token').val(),
    action:'setTag',
    songId:songId,
    tag:songField,
    tagValue:fieldValue
    }
 });
}

function doSearch()
{
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'doSearch',
    keyword:$('#keyword').val()
    },
    success:function(jsonObj){
      $('#dataGrid').empty().append(jsonObj.response);
      $('#keyword').focus();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function refreshLib()
{
  $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'refresh'
    },
    success:function(jsonObj){
      $('#dataGrid').empty().append(jsonObj.response);
      $('#keyword').focus();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function refreshPls()
{
  $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'refreshPls'
    },
    success:function(jsonObj){
      $('#plsList').empty().append(jsonObj.list);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function sortBy(field)
{
  $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'sortBy',
    field:field
    },
    success:function(jsonObj){
      $('#dataGrid').empty().append(jsonObj.response);
      $('#keyword').focus();
      //doSearch();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function setOffset(offsetValue)
{
  $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'offset',
    offset:offsetValue
    },
    success:function(jsonObj){
      $('#dataGrid').empty().append(jsonObj.response);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function mkTagEditable(obj,songId,tag)
{
  $(obj).editable("?c=ajax",{saving:str.ui_saving,editClass:'inlineEdit',extraParams:{
      action:'setTag',
      songId:songId,
      tag:tag,
      token:$('#token').val()
    } });
}

function tagsForm(songId)
{
    $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'id3Form',
    songId:songId
    },
    success:function(jsonObj){
      $('#modal').empty().append(jsonObj.response).jqm().jqmShow();
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function submitId3()
{

  if(trim($('#id3Artist').val()) == '')
  {
    alert(str.err_not_enough_infos);
    $('#id3Artist').focus();
    return false;
  }
  if(trim($('#id3Title').val()) == '')
  {
    alert(str.err_not_enough_infos);
    $('#id3Title').focus();
    return false;
  }

  $.ajax({
    dataType: "json",
   data:{
    token:$('#token').val(),
    action:'submitId3',
    songId:$('#id3SongId').val(),
    artist:$('#id3Artist').val(),
    title:$('#id3Title').val(),
    album:$('#id3Album').val(),
    genre:$('#id3Genre').val(),
    comment:$('#id3Comment').val(),
    year:$('#id3Year').val(),
    number:$('#id3Number').val()
    },
    success:function(jsonObj){
      if(jsonObj == 'ok')
      {
        $('#modal').empty().jqm().jqmHide();
        refreshLib();
      }
      else
      {
        alert(str.err_no_rights);
      }
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
 refreshLib();
}
/***************************** USER PREFS *************************************/

function switchLang(lang)
{
  $.ajax({
   data:{
    token:$('#token').val(),
    action:'switchLang',
    lang:lang
    }
 });
}

function switchSkin(skin)
{
  $.ajax({
   data:{
    token:$('#token').val(),
    action:'switchSkin',
    skin:skin
    }
 });
 $('#screenStyles').attr('href','app/skin/'+skin+'/screen.css');
}

function updateUserIds()
{
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'updateUserIds',
    lastfmUsr:$('#prefLastfmId').val(),
    lastfmPwd:$('#prefLastfmPass').val(),
    mczPwd:$('#prefMczPass').val()
    },
    success:function(jsonObj){
      if(jsonObj.response == 'ok')
      {
        alert(str.ui_changes_saved);
        $('#prefsTab').empty().append(jsonObj.html);
      }
      else
      {
        alert(str.ui_no_changes);
      }
      
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}
/****************************** ADMIN *****************************************/

function userForm(id)
{
  if(id=='empty')
  {
    return;
  }
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'userForm',
    id:id
    },
    success:function(jsonObj){
      $('#userForm').empty().append(jsonObj.html);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function groupForm(id)
{
  if(id=='empty')
  {
    return;
  }
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'groupForm',
    id:id
    },
    success:function(jsonObj){
      $('#groupForm').empty().append(jsonObj.html);
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}

function changeUserStatus(id,status)
{
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'switchUserStatus',
    id:id
    },
    success:function(jsonObj){
      if(!jsonObj)
      {
        alert(str.err_ajax_failed);
      }
    },
    error:function(requestObj,errString,exceptionObj){
      alert(str.err_ajax_failed);
    }
 });
}
function changeUserGroup(id,group)
{
  $.ajax({
  dataType: "json",
   data:{
    token:$('#token').val(),
    action:'changeGroup',
    id:id,
    group:group
    }
 });
}

function addUser()
{
  var name = prompt(str.hlp_enter_user_name, "");
  if(name == null)
  {
    return false;
  }
  if(trim(name) == '')
  {
    alert(str.err_enter_user_name);
    return false;
  }
  if(name !='' && name != null)
  {
    var password = prompt(str.hlp_enter_user_password, GeneratePassword());
    
    $.ajax({
      dataType: "json",
      data:{
        token:$('#token').val(),
        action:'addUser',
        id:name,
        password:password
      },
      success:function(jsonObj)
      {
        if(jsonObj.response == 'ok')
        {
          $('#userForm').empty().append(jsonObj.form);
          $('#usersList').empty().append(jsonObj.list);
        }
        else
        {
          alert(jsonObj.response);
        }
      },
      error:function(requestObj,errString,exceptionObj)
      {
        alert(str.err_ajax_failed);
      }
    });
    
  }
}
function deleteUser()
{
  if($('#usersSelect').val() == 'empty')
  {
    return false;
  }
  if(confirm(str.ui_delete_user))
  {
    $.ajax({
      dataType: "json",
      data:{
        token:$('#token').val(),
        action:'deleteUser',
        id:$('#usersSelect').val()
      },
      success:function(jsonObj)
      {
        if(jsonObj.response == 'ok')
        {
          $('#userForm').empty();
          $('#usersList').empty().append(jsonObj.html);
        }
      },
      error:function(requestObj,errString,exceptionObj)
      {
        alert(str.err_ajax_failed);
      }
    });
  }
}

function userChangePassword(id)
{
  var pwd1 = prompt(str.hlp_enter_new_password);
  if(pwd1 == null)
  {
    return false;
  }
  var pwd2 = prompt(str.hlp_repeat_password);
  if(pwd2 == null)
  {
    return false;
  }
  if(pwd2 != pwd1)
  {
    alert(str.err_password_no_match);
    return false;
  }
  
  
      $.ajax({
      dataType: "json",
      data:{
        token:$('#token').val(),
        action:'userChangePassword',
        id:id,
        password:pwd1
      },
      success:function(jsonObj)
      {
        if(jsonObj.response != 'ok')
        {
          alert(str.err_password_not_changed);
        }
        else
        {
          alert(str.ui_password_changed);
        }
      },
      error:function(requestObj,errString,exceptionObj)
      {
        alert(str.err_ajax_failed);
      }
    });
  
  
}


function setPrefMczPass()
{
  var pwd1 = prompt(str.hlp_enter_new_password);
  if(pwd1 == null)
  {
    return false;
  }
  var pwd2 = prompt(str.hlp_repeat_password);
  if(pwd2 == null)
  {
    return false;
  }
  if(pwd2 != pwd1)
  {
    alert(str.err_password_no_match);
    return false;
  }
  $('#prefMczPass').val(pwd1);
}

function setPrefLastfmPass()
{
  var pwd1 = prompt(str.hlp_enter_new_password);
  if(pwd1 == null)
  {
    return false;
  }
  var pwd2 = prompt(str.hlp_repeat_password);
  if(pwd2 == null)
  {
    return false;
  }
  if(pwd2 != pwd1)
  {
    alert(str.err_password_no_match);
    return false;
  }
  $('#prefLastfmPass').val(pwd1);
}
function addGroup()
{
  var name = prompt(str.hlp_enter_new_group);
  if(name == null)
  {
    return false;
  }
  if(trim(name) == '')
  {
    alert(str.err_enter_group_name);
    return false;
  }
    $.ajax({
      dataType: "json",
      data:{
        token:$('#token').val(),
        action:'addGroup',
        name:name
      },
      success:function(jsonObj)
      {
        if(jsonObj.response != 'ok')
        {
          alert(str.err_group_not_added);
        }
        else
        {
          $('#groupForm').empty().append(jsonObj.form);
          $('#groupsList').empty().append(jsonObj.list);
        }
      },
      error:function(requestObj,errString,exceptionObj)
      {
        alert(str.err_ajax_failed);
      }
    });
}
function deleteGroup()
{
  if($('#groupsSelect').val() == 'empty')
  {
    return false;
  }
    $.ajax({
      dataType: "json",
      data:{
        token:$('#token').val(),
        action:'deleteGroup',
        id:$('#groupsSelect').val()
      },
      success:function(jsonObj)
      {
        if(jsonObj.response != 'ok')
        {
          alert(str.err_group_not_deleted);
        }
        else
        {
          $('#groupForm').empty();
          $('#groupsList').empty().append(jsonObj.list);
        }
      },
      error:function(requestObj,errString,exceptionObj)
      {
        alert(str.err_ajax_failed);
      }
    });
}
function updateGroupRights(obj)
{
  var value;
  var right = obj.id;
  if(obj.checked == true)
  {
    value = 'T';
  }
  else
  {
    value = 'F';
  }
   $.ajax({
      data:{
        token:$('#token').val(),
        action:'updateGroupRights',
        id:$('#groupIdValue').val(),
        right:right,
        value:value
      }
   });
}
